<template>
  <div>
    <el-dialog :title="title" :visible.sync="showUser" width="580px" :before-close="handleClose">
      <div class="marginTop">
        <el-form ref="form" :inline="true" :model="form" :rules="rules" size="small"
          label-width="66px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="form.username" />
          </el-form-item>
          <el-form-item label="电话" prop="phone">
            <el-input v-model.number="form.phone" />
          </el-form-item>
          <el-form-item label="昵称" prop="nickName">
            <el-input v-model="form.nickName" />
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="form.email" />
          </el-form-item>
          <el-form-item label="部门" prop="dept.id">
            <treeselect v-model="form.dept.id" :options="depts" :load-options="loadDepts"
              style="width: 178px" placeholder="选择部门" />
          </el-form-item>
          <el-form-item label="岗位" prop="jobs">
            <el-select v-model="form.jobs" style="width: 178px;height:32px;" multiple
              placeholder="请选择" @remove-tag="deleteTag" @change="changeJob">
              <el-option v-for="item in jobs" :key="item.name" :label="item.name"
                :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="性别">
            <el-radio-group v-model="form.gender" style="width: 178px">
              <el-radio label="男">男</el-radio>
              <el-radio label="女">女</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="状态">
            <el-radio-group v-model="form.enabled">
              <!-- :disabled="form.id === userInfo.userIds" -->
              <el-radio v-for="item in user_status" :key="item.id" :label="item.value">
                {{ item.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item style="margin-bottom: 0;" label="角色" prop="roles">
            <el-select v-model="form.roles" style="width: 437px" multiple placeholder="请选择"
              @remove-tag="deleteTag" @change="changeRole">
              <el-option v-for="item in roles" :key="item.name" :label="item.name"
                :value="item.id" />
              <!-- :disabled="level !== 1 && item.level <= level" -->
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer mt20">
          <el-button @click="handleClose">取消</el-button>
          <el-button :loading="loading" type="primary" @click="submitForm">确认</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { isPhone } from '@/utils/validate'
import { mapGetters } from 'vuex'
import { getDepts, getDeptSuperior } from '@/api/system/dept'
import { add, edit } from '@/api/system/user'
import { getAllJob } from '@/api/system/job'
import { getAll, getLevel } from '@/api/system/role'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { LOAD_CHILDREN_OPTIONS } from '@riophae/vue-treeselect'
let userRoles = []
let userJobs = []
export default {
  components: {
    Treeselect
  },
  props: {
    editData: {
      type: Object,
      default: () => { }
    },
    title: {
      type: String,
      default: ''
    },
    showUser: {
      type: Boolean,
      default: false
    },
    logisticsData: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    // 自定义验证
    const validPhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入电话号码'))
      } else if (!isPhone(value)) {
        callback(new Error('请输入正确的11位手机号码'))
      } else {
        callback()
      }
    }
    return {
      level: 3,
      depts: [],
      roles: [],
      jobs: [],
      user_status: [
        { label: '激活', id: 1, value: true },
        { label: '禁用', id: 2, value: false }
      ],
      loading: false,
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        nickName: [
          { required: true, message: '请输入用户昵称', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        'dept.id': [
          { required: true, message: '请选择所属部门', trigger: 'change' }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { required: true, trigger: 'blur', validator: validPhone }
        ],
        roles: [
          { required: true, message: '请选择角色', trigger: 'blur' }
        ]
      },
      form: {
        username: '',
        phone: '',
        nickName: '',
        email: '',
        dept: { id: null },
        jobs: [],
        gender: '男',
        enabled: false,
        roles: []
      }
    }
  },
  computed: {
    ...mapGetters(['userInfo'])
  },
  watch: {
    showUser() {
      if (this.showUser) this.initForm()
    }
  },
  methods: {
    initForm() {
      let pamrms = {
        username: '',
        phone: '',
        nickName: '',
        email: '',
        dept: { id: null },
        jobs: [],
        gender: '男',
        enabled: false,
        roles: []
      }
      if (this.title === '编辑用户') {
        this.editData.enabled = this.editData.enabled
        pamrms = Object.assign(this.form, this.editData)
        this.getSupDepts(pamrms.dept.id)
        this.getJobs(this.form.dept.id)
        userRoles = []
        userJobs = []
        const roles = []
        const jobs = []
        console.log('编辑参数', pamrms)
        pamrms.roles.forEach(function (role, index) {
          roles.push(role.id)
          // 初始化编辑时候的角色
          const rol = { id: role.id }
          userRoles.push(rol)
        })
        if (pamrms.jobs && pamrms.jobs.length) {
          pamrms.jobs.forEach(function (job, index) {
            jobs.push(job.id)
            // 初始化编辑时候的岗位
            const data = { id: job.id }
            userJobs.push(data)
          })
        }
        pamrms.roles = roles
        pamrms.jobs = jobs
      } else this.getDepts()
      this.getRoleLevel()
      this.getJobs()
      this.getRoles()
      this.form = pamrms
    },
    getSupDepts(deptId) {
      getDeptSuperior(deptId).then(res => {
        this.depts = res.list.map(function (obj) {
          if (obj.hasChildren && !obj.children) {
            obj.children = null
          }
          return obj
        })
      })
    },
    // 获取弹窗内岗位数据
    getJobs() {
      getAllJob().then(res => {
        this.jobs = res.list
      }).catch(() => { })
    },
    // 获取权限级别
    getRoleLevel() {
      getLevel().then(res => {
        this.level = res.level
      }).catch(() => { })
    },
    // 获取弹窗内角色数据
    getRoles() {
      getAll().then(res => {
        this.roles = res
      }).catch(() => { })
    },
    getDepts() {
      getDepts({ enabled: true }).then(res => {
        this.depts = res.list.map(function (obj) {
          if (obj.hasChildren) {
            obj.children = null
          }
          return obj
        })
      })
    },
    // 获取弹窗内部门数据
    loadDepts({ action, parentNode, callback }) {
      if (action === LOAD_CHILDREN_OPTIONS) {
        getDepts({ enabled: true, pid: parentNode.id }).then(res => {
          parentNode.children = res.list.map(function (obj) {
            if (obj.hasChildren) {
              obj.children = null
            }
            return obj
          })
          setTimeout(() => {
            callback()
          }, 200)
        })
      }
    },
    // 关闭弹框
    handleClose() {
      this.$emit('update:showUser', false)
    },
    submitForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.title === '新增用户') {
            this.addUser()
          } else this.editUser()
        } else {
          return false
        }
      })
    },
    // 编辑
    editUser() {
      const jobs = []
      this.form.jobs.forEach(function (data, index) {
        const job = { id: data }
        jobs.push(job)
      })
      this.form.jobs = jobs
      const roles = []
      this.form.roles.forEach(function (data, index) {
        const role = { id: data }
        roles.push(role)
      })
      this.form.roles = roles
      edit(this.form).then(res => {
        this.handleClose()
        this.$emit('search')
        this.$message.success('操作成功~')
      })
    },
    // 新增
    addUser() {
      const params = this.form
      const jobs = []
      params.jobs.forEach(function (data, index) {
        const job = { id: data }
        jobs.push(job)
      })
      params.jobs = jobs
      const roles = []
      params.roles.forEach(function (data, index) {
        const role = { id: data }
        roles.push(role)
      })
      params.roles = roles
      add(params).then(res => {
        this.handleClose()
        this.$emit('search')
        this.$message.success('操作成功~')
      }).catch(() => {
        this.handleClose()
      })
    },
    deleteTag(value) { },
    changeRole(value) {
      userRoles = []
      value.forEach(function (data, index) {
        const role = { id: data }
        userRoles.push(role)
      })
    },
    changeJob(value) {
      userJobs = []
      value.forEach(function (data, index) {
        const job = { id: data }
        userJobs.push(job)
      })
    }
  }
}
</script>
<style scoped lang="scss">
/deep/.el-dialog__title {
  color: #333;
  font-weight: bold;
  font-size: 16px;
}
/deep/.dialog-footer {
  text-align: right;
  padding-right: 35px;
}
/deep/.el-form-item--small.el-form-item {
  margin-bottom: 25px;
}
</style>
